package com.market.cash.ui.presenter

import com.market.cash.R
import com.market.cash.base.BaseFragment
import com.market.cash.http.ApiService
import com.market.cash.http.ApiService.addCommonParams
import com.market.cash.http.IHttpCallback
import com.market.cash.pro.ProPresenter
import com.market.cash.ui.fragment.DataSafetyFragment
import com.market.cash.ui.fragment.HomeFragment
import com.market.cash.ui.fragment.RepayFragment
import com.market.cash.ui.fragment.UserFragment
import com.market.cash.ui.view.ICashRootMainView
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/17 11:59
 * @Annotation：主页面 Presenter 实现
 */
class CashRootMainPresenter(private val iView: ICashRootMainView): ProPresenter(iView) {
    //val 是不可变的 var 可变的
    private val tabImageNormal = arrayListOf(
        R.mipmap.cash_tab_home_normal,
        R.mipmap.cash_tab_repay_normal,
        R.mipmap.cash_tab_data_afety_normal,
        R.mipmap.cash_tab_user_normal
    )

    private val tabImageSelect = arrayListOf(
        R.mipmap.cash_tab_home_select,
        R.mipmap.cash_tab_repay_select,
        R.mipmap.cash_tab_data_afety_select,
        R.mipmap.cash_tab_user_select
    )

    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    private val fragments = ArrayList<BaseFragment>()
    private var curtIndex = 0

    /**
     * 加载Tabbar数据
     */
    fun loadCashRootTabList(){
        tabList.clear()
        //tab
        for (i in 0 until tabImageNormal.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabImageSelected", tabImageSelect[i])
            tabObj.put("tabImageNormal", tabImageNormal[i])
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        iView.showCashRootTabList(tabList)
    }

    /**
     * 加载FragmentList
     */
    fun loadCashRootFragmentList(){
        fragments.add(HomeFragment())//首页
        fragments.add(RepayFragment())//还款
        fragments.add(DataSafetyFragment())//数据安全
        fragments.add(UserFragment())//个人中心

        setCashRootCurrentItemIndex(0)
    }

    /**
     * 切换Tab
     */
    fun setCashRootCurrentItemIndex(index: Int) {
        curtIndex = index
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                index -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        iView.notifyTabDataChanged()

        val fragment = fragments[curtIndex]
        iView.showCashRootFragment(fragment,curtIndex)
    }

    /**
     * 获取总流程
     */
    fun loadCashRootProcessAction() {
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_PROCESS_URL)
        val params = JSONObject().addCommonParams().apply {
            put("path", ApiService.API_PATH.CASHROOT_API_PROCESS_PATH)
        }
        doCashRootPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    allStepTitles.put("Account Info")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    allSteps.put("account_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }

                    SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_PROCESS, obj.toString())
                    //通知全局流程刷新完成
                    iView.getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PROCESS_REFRESHED))
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取产品列表
     * 存在待还款的产品 ，需要直接展示Repay，否则显示可申请产品列表
     */
    fun loadCashRootProductListAction(){
        val params = JSONObject()
            .addCommonParams()
            .apply {
                put("path", ApiService.API_PATH.CASHROOT_API_LOAN_PRODUCT_LIST_PATH)
                put("mobile", SharedHelper.getCashRootSPString(SharedHelper.CashRoot_SPKEY.CASHROOT_MOBILE))
            }
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CASHROOT_API_PRODUCT_LIST_URL)
        doCashRootPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_PRODUCT,data.optString("obj"))
                iView.getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESHED))

                var showTabIndex = 0
                val objArray = data.optJSONArray("obj")
                if (objArray != null) {
                    //可申请的产品数量
                    var productCount = 0
                    for (i in 0..<objArray.length()){
                        val item = objArray.optJSONObject(i)
                        //可申请的产品
                        if (item.optString("activeFlag") == "YES"){
                            productCount++
                        }

                        if ("REPAYMENT" == item.optString("status")){
                            showTabIndex = 1
                        }
                    }
                    //保存用户VIP等级
                    saveCashRootUserVip(productCount)
                }

//                if (isCheck){
//                    //默认选中第1个
//                    setCashRootCurrentItemIndex(showTabIndex)
//                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                iView.getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_FINISHED))
            }
        })
    }

    /**
     * 保存用户Vip等级
     */
    fun saveCashRootUserVip(pCount: Int){
        if (pCount <= 1){
            SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_VIP,1)
        } else if (pCount > 4){
            SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_VIP,3)
        } else {
            SharedHelper.saveCashRootSPData(SharedHelper.CashRoot_SPKEY.CASHROOT_VIP,2)
        }
    }
}